package com.wu.project.admin.service.impl;

import com.wu.project.admin.component.JsonResult;
import com.wu.project.admin.dao.LogDao;
import com.wu.project.admin.entity.LogEntity;
import com.wu.project.admin.entity.LogQueryVO;
import com.wu.project.admin.entity.PageData;
import com.wu.project.admin.property.Constants;
import com.wu.project.admin.service.LogService;
import com.wu.project.admin.util.CommonResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xuan
 */
@Service
public class LogServiceImpl implements LogService {

    @Autowired
    LogDao logDao;

    private final Logger logger = LoggerFactory.getLogger(LogServiceImpl.class);

    @Async("taskExecutor")
    @Override
    public void saveCommonLog(LogEntity logEntity) {
        logEntity.setTime(CommonResultUtil.Instance.getNowStringTime());
        if (logEntity.getType() == null) {
            logEntity.setType(Constants.DEFAULT_TYPE);
        }
        logDao.insetLogToDb(logEntity);
    }

    @Async("taskExecutor")
    @Override
    public void saveOperatorLog(LogEntity logEntity) {
        logEntity.setTime(CommonResultUtil.Instance.getNowStringTime());
        logEntity.setType(Constants.OPERATOR_TYPE);
        logDao.insetLogToDb(logEntity);
    }

    @Async("taskExecutor")
    @Override
    public void saveExceptionLog(LogEntity logEntity) {
        logEntity.setTime(CommonResultUtil.Instance.getNowStringTime());
        logEntity.setType(Constants.EXCEPTION_TYPE);
        logDao.insetLogToDb(logEntity);
    }

    @Override
    public JsonResult getLogList(LogQueryVO logQueryVO) {
        Integer offset = CommonResultUtil.Instance.getOffset(logQueryVO.getPageNum(), logQueryVO.getPageSize());
        logQueryVO.setOffset(offset);

        List<LogEntity> logEntityList = logDao.queryLogs(logQueryVO);
        Integer size = logDao.queryLogsSize(logQueryVO);
        PageData<List<LogEntity>> pageData = new PageData<>();
        pageData.setPageNum(logQueryVO.getPageNum());
        pageData.setPageSize(logQueryVO.getPageSize());
        pageData.setTotal(size);
        pageData.setData(logEntityList);
        return CommonResultUtil.Instance.success(pageData);
    }
}
